package example;

import commom.ColorAndXY;
import commom.RGB;
import javafx.stage.Stage;
import sun.awt.TimedWindowEvent;
import util.Util;
import commom.XY;
import example.neon.JPanelImgAndMsgContent;
import example.neon.JPanelSettingContent;
import example.neon.MainJFrameNeon;

import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class NeonAbyssAutoFish {

    static Dimension screenSize;
    // 截图的图像范围(px)
    static int rangeByImage = 100;
    static Robot robot;
    static Map<Integer, String> keyMap = new HashMap<>();

    static {
        keyMap.put(KeyEvent.VK_A, "A");
        keyMap.put(KeyEvent.VK_S, "S");
        keyMap.put(KeyEvent.VK_D, "D");
        keyMap.put(KeyEvent.VK_W, "W");
    }

    static ColorAndXY[] colorAndXYA = Util.readColorAndXYByFilePath("img/A.png");
    static ColorAndXY[] colorAndXYS = Util.readColorAndXYByFilePath("img/S.png");
    static ColorAndXY[] colorAndXYD = Util.readColorAndXYByFilePath("img/D.png");
    static ColorAndXY[] colorAndXYW = Util.readColorAndXYByFilePath("img/W.png");
    static ColorAndXY[] colorAndXYOk = Util.readColorAndXYByFilePath("img/ok.png");

    static double similar = 0.5;
    static JPanelImgAndMsgContent consoleLog = MainJFrameNeon.jPanelImgAndMsgContent;
    static JPanelSettingContent setting = MainJFrameNeon.jPanelSettingContent;

    /**
     * 获取鼠标位置
     * 根据鼠标位置截图
     *
     * @return
     */
    public static BufferedImage screenCapture() throws IOException {
        Point location = MouseInfo.getPointerInfo().getLocation();
        int x1 = location.x - rangeByImage;
        int y1 = location.y - rangeByImage;
        if (x1 <= 0) x1 = 0;
        if (y1 <= 0) y1 = 0;

        Rectangle rectangle = new Rectangle(x1, y1, 300, 300);
        return robot.createScreenCapture(rectangle);
    }

    /**
     * 识别WASD
     * 返回按键码 -1没找到 65 A 68 D ...
     */
    public static int findWasd(BufferedImage bufferedImage) {
        int key = -1;
        XY isFind;
        // 性能差的话待优化 wasd一起找 不一个一个找
        if ((isFind = Util.findTheLocationOfSimilarImages(bufferedImage, colorAndXYA, similar)) != null) {
            key = KeyEvent.VK_A;
//            try {
//                Point location = MouseInfo.getPointerInfo().getLocation();
//                int x = location.x - 100 + isFind.x;
//                int y = location.y - 100 + isFind.y;
//                BufferedImage screenCapture = robot.createScreenCapture(new Rectangle(x, y, 20, 22));
//                ImageIO.write(screenCapture, "jpg", new File("C:\\\\Users\\\\Administrator\\\\Desktop\\\\projects\\\\search-img\\\\img\\\\A\\\\" + System.currentTimeMillis() + ".png"));
//
//                screenCapture = robot.createScreenCapture(new Rectangle(x - 20, y - 20, 40, 42));
//                ImageIO.write(screenCapture, "jpg", new File("C:\\\\Users\\\\Administrator\\\\Desktop\\\\projects\\\\search-img\\\\img\\\\A\\\\" + System.currentTimeMillis() + "-1.png"));
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
        } else if ((isFind = Util.findTheLocationOfSimilarImages(bufferedImage, colorAndXYS, similar)) != null) {
            key = KeyEvent.VK_S;
        } else if ((isFind = Util.findTheLocationOfSimilarImages(bufferedImage, colorAndXYD, similar)) != null) {
            key = KeyEvent.VK_D;
        } else if ((isFind = Util.findTheLocationOfSimilarImages(bufferedImage, colorAndXYW, similar)) != null) {
            key = KeyEvent.VK_W;
        }
        if (key != -1) {
            System.out.println("查找结果" + true + ", 按键：" + keyMap.get(key) + ", xy=" + isFind);
            consoleLog.pushMsg("识别到按键：" + keyMap.get(key));
        }
        return key;
    }

    public static boolean findOk() throws IOException {
        long startTime = System.currentTimeMillis() - 1;
        // 超过2s没找到
        while (System.currentTimeMillis() - startTime <= 2000) {
            BufferedImage bufferedImage = screenCapture();
//            ImageIO.write(bufferedImage, "png", new File("C:\\Users\\Administrator\\Desktop\\projects\\search-img\\img\\ok\\" + System.currentTimeMillis() + ".png"));
//            System.out.println("开始截图：" + location.x + "," + location.y);
            XY xy = Util.findTheLocationOfSimilarImages(bufferedImage, colorAndXYOk, similar);
            if (xy != null)
                return true;
            System.out.print("?");
        }
        return false;
    }

    /**
     * 按下按键 KeyEvent.?
     */
    public static void keyClick(int key) throws InterruptedException {
        robot.keyPress(key);
        Thread.sleep(1);
        robot.keyRelease(key);
    }

    public static void main(String[] args) throws Exception {
        MainJFrameNeon test = new MainJFrameNeon();
        test.addWindowStateListener(new WindowAdapter() {
            @Override
            public void windowStateChanged(WindowEvent e) {
                super.windowStateChanged(e);
                TimedWindowEvent timedWindowEvent = (TimedWindowEvent) e;
                System.out.println("窗口激活：" + timedWindowEvent.getNewState());
            }
        });
        robot = new Robot();
        int i = 0;
        int maxWaitTime = 5000;
        long startTime = System.currentTimeMillis();
        while (true) {
            BufferedImage bufferedImage = screenCapture();
            bufferedImage.getRGB(0, 0);
            consoleLog.setImage(bufferedImage);
            // ImageIO.write(bufferedImage, "png", new File("C:\\Users\\Administrator\\Desktop\\projects\\search-img\\img\\wasd\\" + System.currentTimeMillis() + ".png"));
            int wasdKey = findWasd(bufferedImage);
            if (wasdKey != -1) {
                // 最多1秒左右就出OK的圈
                boolean ok = findOk();
                if (ok) {
                    keyClick(wasdKey);
                    if (setting.jPanelCheckboxDance.isCheck) {
                        Thread.sleep(1300);
                        consoleLog.pushMsg("自动跳舞中...");
                    } else {
                        consoleLog.pushMsg("咬钩了！起√！");
                        Thread.sleep(1600);
                        if (setting.jPanelCheckboxRoom.isCheck) {
                            keyClick(KeyEvent.VK_E);
                        } else {
                            robot.mousePress(InputEvent.BUTTON3_DOWN_MASK);
                            Thread.sleep(1);
                            robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK);
                        }
                        startTime = System.currentTimeMillis();
                        String msg = setting.jPanelCheckboxRoom.isCheck ? "正在按E继续钓鱼..." : "正在使用咸鱼枪继续钓鱼...";
                        consoleLog.pushMsg(msg);
                    }
                }
            }
            Thread.sleep(10);
            if (setting.jPanelCheckboxRoom.isCheck && System.currentTimeMillis() - startTime > maxWaitTime) {
                String msg = "可能挡住了，手动使用咸鱼枪试试";
                consoleLog.pushMsg(msg);
                startTime = System.currentTimeMillis();
            }
        }
    }
}
